﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace TerminationCall.Core {

    public class TileSetSaver {

        private BinaryWriter _binaryWriter;

        public void Save(string fileName, TileSet tileSet) {

            _binaryWriter = new BinaryWriter(File.OpenWrite(fileName));

            _binaryWriter.Write(Path.GetFileName(tileSet.FileName));
            _binaryWriter.Write(tileSet.Name);

            int horizontalTiles = tileSet.Tiles.GetLength(0);
            int verticalTiles = tileSet.Tiles.GetLength(1);

            _binaryWriter.Write(horizontalTiles);
            _binaryWriter.Write(verticalTiles);

            for (int x = 0; x < horizontalTiles; x++) {

                for (int y = 0; y < verticalTiles; y++) {

                    Tile tile = tileSet.Tiles[x, y];

                    WriteTileNumbers(tile.ParentTile);

                    WriteTileNumbers(tile.ChildTileField.GetTile(TileFields.TopTile));
                    WriteTileNumbers(tile.ChildTileField.GetTile(TileFields.RightTopTile));
                    WriteTileNumbers(tile.ChildTileField.GetTile(TileFields.LeftTopTile));
                    WriteTileNumbers(tile.ChildTileField.GetTile(TileFields.RightMiddleTile));
                    WriteTileNumbers(tile.ChildTileField.GetTile(TileFields.LeftMiddleTile));
                    WriteTileNumbers(tile.ChildTileField.GetTile(TileFields.BottomTile));
                    WriteTileNumbers(tile.ChildTileField.GetTile(TileFields.RightBottomTile));
                    WriteTileNumbers(tile.ChildTileField.GetTile(TileFields.LeftBottomTile));

                }

            }

            _binaryWriter.Write(tileSet.TileObjectGroups.Count);

            foreach (TileObjectGroup tileObjectGroup in tileSet.TileObjectGroups) {

                _binaryWriter.Write(tileObjectGroup.Rectangle.X);
                _binaryWriter.Write(tileObjectGroup.Rectangle.Y);
                _binaryWriter.Write(tileObjectGroup.Rectangle.Width);
                _binaryWriter.Write(tileObjectGroup.Rectangle.Height);
                _binaryWriter.Write(tileObjectGroup.Name);

            }

            _binaryWriter.Close();        

        }

        private void WriteTileNumbers(Tile tile) {
            if (tile != null) {
                _binaryWriter.Write(tile.NumberX);
                _binaryWriter.Write(tile.NumberY);
            } else {
                _binaryWriter.Write(-1);
                _binaryWriter.Write(-1);
            }
        }

    }

}
